package client_commands;

import java.util.StringTokenizer;

import streaming.Call;
import client.ClientApplication;
import client.ClientBindObject;

public class STOP_CALLCommand extends Command {

	public STOP_CALLCommand(String parameter) {
		setCode(STOP_CALL);
		setParameter(parameter);
	}
	
	
	@Override
	public boolean executeCommand(ClientApplication theApp) {

		String parameter = getParameter();
		
		if ( parameter == null ) {
			return false;
		}
		
		StringTokenizer tokens = new StringTokenizer(parameter);
		
		if ( tokens.countTokens() != 2 ) {
			return false;
		}
		
		String username = tokens.nextToken();
		String flag = tokens.nextToken();
		
		ClientBindObject cbo = ClientApplication.clientBinding.get(username);
		
		if ( cbo == null || cbo.getConnection() == null ) {
			return false;
		}
		
		Call call = cbo.getCall();
		
		if ( flag.equals("C") ) {
			// conversation
			if ( call != null ) {
				call.hangUpCall();
				cbo.getDialog().getStreamingPanel().removeListeners();
				cbo.setCall(null);
			}
		}
		else if ( flag.equals("W") ) {
			// waiting
			if ( cbo.getDialog() != null ) {
				cbo.getDialog().getStreamingPanel().showNoVideoPanel();
				cbo.getDialog().getStreamingPanel().getNoButton().doClick();
			}
			// ne mora da se odgovori, jer getNoButton().doClick() izazove vracanje odgovora
			// videti CALL_REQUESTCommand - kao da je user odovorio sa No
//			cbo.getConnection().writeData("CLIENT_RESPONSE N");
		}
		else {
			System.out.println("NO stop command");
			return false;
		}
		
		return true;
	}
	
}
